﻿Imports TodoMicroSolutionPackV1.dal.dto
Imports TodoMicroSolutionPackV1.dal.dao
Imports TodoMicroSolutionPackV1.dal.dto.ubicacion
Imports TodoMicroSolutionPackV1.facturacion.dal.dto
Imports TodoMicroSolutionPackV1.productos.dal.dto
Imports TodoMicroSolutionPackV1.entidades.dal.dto
Imports TodoMicroSolutionPackV1.afipWs
Imports System.ComponentModel
Imports NHibernate
Imports NHibernate.Cfg
Imports System.Xml
Imports NHibernate.Validator.Engine
Imports NHibernate.Validator.Exceptions

Public Class frmComprobanteEdit
    Private Const frmAnchoInicial As Integer = 1068
    Private Const frmAlturaInicial As Integer = 597
    Private Const grdItemsAnchoInicial As Integer = 905
    Private Const grdItemsAlturaInicial As Integer = 177
    Private Const btnGuardarPosXInicial As Integer = 389
    Private Const btnGuardarPosYInicial As Integer = 514
    Private Const btnGenerarXMLPosXInicial As Integer = 389
    Private Const btnGenerarXMLPosYInicial As Integer = 514
    Private Const btnEliminarPosXInicial As Integer = 265
    Private Const btnEliminarPosYInicial As Integer = 515
    Private Const btnCancelarPosXInicial As Integer = 531
    Private Const btnCancelarPosYInicial As Integer = 514
    Private Const lblTotalPosXInicial As Integer = 926
    Private Const lblTotalPosYInicial As Integer = 420
    Private Const txtTotalPosXinicial As Integer = 977
    Private Const txtTotalPosYInicial As Integer = 420
    Private Const lblPagoPosXInicial As Integer = 926
    Private Const lblPagoPosYInicial As Integer = 446
    Private Const txtPagoPosXInicial As Integer = 978
    Private Const txtPagoPosYInicial As Integer = 446
    Private Const lblVueltoPosXInicial As Integer = 926
    Private Const lblVueltoPosYInicial As Integer = 472
    Private Const txtVueltoPosXInicial As Integer = 978
    Private Const txtVueltoPosYInicial As Integer = 472
    Private Const btnAgregarItemPosXInicial As Integer = 932
    Private Const btnBorrarItemPosXInicial As Integer = 932
    Private Const btnBorrarTodoPosXInicial As Integer = 932
    Private Const btnXMLPosXInicial As Integer = 929
    Private Const btnXMLPosYInicial As Integer = 527
    Private Const btnModificarItemPosXInicial As Integer = 932
    Private Const cmbNumeroDespachoPosXInicial As Integer = 794
    Private Const lblNumeroDespachoPosXInicial As Integer = 794
    Private Const cmbDepositoPosXInicial As Integer = 794
    Private Const lblDepositoPosXInicial As Integer = 794
    Private Const cmbIvaPosXInicial As Integer = 529
    Private Const lblIvaPosXInicial As Integer = 529
    Private Const txtPrecioNetoPosXInicial As Integer = 597
    Private Const lblPrecioNetoPosXInicial As Integer = 597
    Private Const txtPrecioBrutoPosXInicial As Integer = 699
    Private Const lblPrecioBrutoPosXInicial As Integer = 699
    Private Const cmbPuntoVentaPosXInicial As Integer = 694
    Private Const lblPuntoVentaPosXInicial As Integer = 694
    Private Const lblTipoDocumentoPosXInicial As Integer = 694
    Private Const cmbTipoDocumentoPosXInicial As Integer = 694
    Private Const lblCondicionesVentaPosXInicial As Integer = 694
    Private Const cmbCondicionesVentaPosXInicial As Integer = 694
    Private Const lblRemitoPosXInicial As Integer = 694
    Private Const txtRemitoPosXInicial As Integer = 694
    Private Const lblNumeroComprobantePosXInicial As Integer = 828
    Private Const txtNumeroComprobantePosXInicial As Integer = 828
    Private Const lblNumeroDocumentoPosXInicial As Integer = 828
    Private Const txtNumeroDocumentoPosXInicial As Integer = 828
    Private Const lblCondicionIvaPosXInicial As Integer = 828
    Private Const cmbCondicionIvaPosXInicial As Integer = 828
    Private Const lblCAEPosXInicial As Integer = 697
    Private Const txtCAEPosXInicial As Integer = 697
    Private Const chkComprobanteAceptadoPosXInicial As Integer = 969
    Private Const txtRazonSocialAnchoInicial As Integer = 675
    Private Const txtDomicilioAnchoInicial As Integer = 675
    Private Const cmbLocalidadAnchoInicial As Integer = 364
    Private Const txtDescripcionAnchoInicial As Integer = 235


    Private miComprobante As New comprobante
    Private itemList As New BindingList(Of comprobanteItem)
    Private cliente As entidad
    Private _session As ISession
    Private DAOFactory As NhibernateDAOFactory

    Dim rpt As New rptComprobante

    Private automatic As Boolean = True
    Private isLoading As Boolean = False

    Protected ReadOnly Property Session As ISession
        Get
            If _session Is Nothing Then
                _session = NhibernateSessionFactory.getSession
            End If
            Return _session
        End Get
    End Property

    Private Sub frmComprobanteEdit_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
        If Not _session Is Nothing Then
            _session.Dispose()
        End If
    End Sub

    Private Sub frmComprobanteEdit_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        grdItems.Width = grdItemsAnchoInicial + Me.Width - frmAnchoInicial
        grdItems.Height = grdItemsAlturaInicial + Me.Height - frmAlturaInicial
        btnGuardar.Left = (Me.Width / 2 - btnGuardar.Width / 2)
        btnGuardar.Top = btnGuardarPosYInicial + Me.Height - frmAlturaInicial
        btnGenerarXML.Left = (Me.Width / 2 - btnGenerarXML.Width / 2)
        btnGenerarXML.Top = btnGenerarXMLPosYInicial + Me.Height - frmAlturaInicial
        btnEliminar.Left = btnGenerarXML.Left - 20 - btnEliminar.Width
        btnEliminar.Top = btnEliminarPosYInicial + Me.Height - frmAlturaInicial
        txtRazonSocial.Width = txtRazonSocialAnchoInicial + Me.Width - frmAnchoInicial
        txtDomicilio.Width = txtDomicilioAnchoInicial + Me.Width - frmAnchoInicial
        cmbLocalidad.Width = cmbLocalidadAnchoInicial + Me.Width - frmAnchoInicial
        txtDescripcion.Width = txtDescripcionAnchoInicial + Me.Width - frmAnchoInicial
        lblPuntoVenta.Left = lblPuntoVentaPosXInicial + Me.Width - frmAnchoInicial
        cmbPuntoVenta.Left = cmbPuntoVentaPosXInicial + Me.Width - frmAnchoInicial
        lblTipoDocumento.Left = lblTipoDocumentoPosXInicial + Me.Width - frmAnchoInicial
        cmbTipoDocumento.Left = cmbTipoDocumentoPosXInicial + Me.Width - frmAnchoInicial
        lblCondicionesVenta.Left = lblCondicionesVentaPosXInicial + Me.Width - frmAnchoInicial
        cmbCondicionesVenta.Left = cmbCondicionesVentaPosXInicial + Me.Width - frmAnchoInicial
        lblRemito.Left = lblRemitoPosXInicial + Me.Width - frmAnchoInicial
        txtRemito.Left = txtRemitoPosXInicial + Me.Width - frmAnchoInicial
        lblNumeroComprobante.Left = lblNumeroComprobantePosXInicial + Me.Width - frmAnchoInicial
        txtNumeroComprobante.Left = txtNumeroComprobantePosXInicial + Me.Width - frmAnchoInicial
        lblNumeroDocumento.Left = lblNumeroDocumentoPosXInicial + Me.Width - frmAnchoInicial
        txtNumeroDocumento.Left = txtNumeroDocumentoPosXInicial + Me.Width - frmAnchoInicial
        lblCondicionIVA.Left = lblCondicionIvaPosXInicial + Me.Width - frmAnchoInicial
        cmbCondicionIVA.Left = cmbCondicionIvaPosXInicial + Me.Width - frmAnchoInicial
        lblCAE.Left = lblCAEPosXInicial + Me.Width - frmAnchoInicial
        txtCAE.Left = txtCAEPosXInicial + Me.Width - frmAnchoInicial
        lblNumeroDespacho.Left = lblNumeroDespachoPosXInicial + Me.Width - frmAnchoInicial
        cmbNumeroDespacho.Left = cmbNumeroDespachoPosXInicial + Me.Width - frmAnchoInicial
        lblDeposito.Left = lblDepositoPosXInicial + Me.Width - frmAnchoInicial
        cmbDeposito.Left = cmbDepositoPosXInicial + Me.Width - frmAnchoInicial
        lblIVA.Left = lblIvaPosXInicial + Me.Width - frmAnchoInicial
        cmbIVA.Left = cmbIvaPosXInicial + Me.Width - frmAnchoInicial
        lblPrecioNeto.Left = lblPrecioNetoPosXInicial + Me.Width - frmAnchoInicial
        txtPrecioNeto.Left = txtPrecioNetoPosXInicial + Me.Width - frmAnchoInicial
        lblPrecioBruto.Left = lblPrecioBrutoPosXInicial + Me.Width - frmAnchoInicial
        txtPrecioBruto.Left = txtPrecioBrutoPosXInicial + Me.Width - frmAnchoInicial
        btnAgregarItem.Left = btnAgregarItemPosXInicial + Me.Width - frmAnchoInicial
        btnBorrarItem.Left = btnBorrarItemPosXInicial + Me.Width - frmAnchoInicial
        btnBorrarTodo.Left = btnBorrarTodoPosXInicial + Me.Width - frmAnchoInicial
        btnModificarItem.Left = btnModificarItemPosXInicial + Me.Width - frmAnchoInicial
        lblTotal.Left = lblTotalPosXInicial + Me.Width - frmAnchoInicial
        txtTotal.Left = txtTotalPosXinicial + Me.Width - frmAnchoInicial
        lblPago.Left = lblPagoPosXInicial + Me.Width - frmAnchoInicial
        txtPago.Left = txtPagoPosXInicial + Me.Width - frmAnchoInicial
        lblVuelto.Left = lblVueltoPosXInicial + Me.Width - frmAnchoInicial
        txtVuelto.Left = txtVueltoPosXInicial + Me.Width - frmAnchoInicial
        lblTotal.Top = lblTotalPosYInicial + Me.Height - frmAlturaInicial
        txtTotal.Top = txtTotalPosYInicial + Me.Height - frmAlturaInicial
        lblPago.Top = lblPagoPosYInicial + Me.Height - frmAlturaInicial
        txtPago.Top = txtPagoPosYInicial + Me.Height - frmAlturaInicial
        lblVuelto.Top = lblVueltoPosYInicial + Me.Height - frmAlturaInicial
        txtVuelto.Top = txtVueltoPosYInicial + Me.Height - frmAlturaInicial

    End Sub

    Private Sub frmComprobanteEdit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        loadAll()
    End Sub
    Private Sub loadAll()
        isLoading = True

        DAOFactory = New NhibernateDAOFactory(Session)
        comunes.populateCombobox(DAOFactory.getConstanteDAO.getConstantes("facturacion", "comprobante"), "valor", "codigo", cmbTipo)
        comunes.populateCombobox(DAOFactory.getConstanteDAO.getConstantes("facturacion", "documento"), "valor", "codigo", cmbTipoDocumento)
        comunes.populateCombobox(DAOFactory.getConstanteDAO.getConstantes("facturacion", "alicuota_iva"), "valor", "codigo", cmbIVA)
        comunes.populateCombobox(DAOFactory.getConstanteDAO.getConstantes("facturacion", "unidades_medida"), "valor", "codigo", cmbUMedida)
        comunes.populateCombobox(DAOFactory.getConstanteDAO.getConstantes("facturacion", "condicion_venta"), "valor", "codigo", cmbCondicionesVenta)
        comunes.populateCombobox(DAOFactory.getConstanteDAO.getConstantes("facturacion", "condicion_iva_a"), "valor", "codigo", cmbCondicionIVA)
        comunes.populateCombobox(DAOFactory.getProductoDAO.FindAll, "codigo", "id", cmbCodigo)
        comunes.populateCombobox(DAOFactory.getProvinciaDAO.FindAll, "nombre", "id", cmbProvincia)
        txtCAE.Text = ""
        txtNumeroDocumento.Text = ""
        txtRazonSocial.Text = ""


        comunes.populateCombobox(DAOFactory.getPuntoVentaDAO.getPuntosDeVentaPorEmpresa(DAOFactory.getEmpresaDAO.FindByID(1)), "numero", "id", cmbPuntoVenta)

        grdItems.DataSource = itemList

        AddHandler itemList.ListChanged, AddressOf itemList_Change

        isLoading = False

        updateUltimoNumeroComprobante()
    End Sub
    Public Sub showAutomaticMode()
        cmbTipoDocumento.Enabled = False
        cmbCondicionIVA.Enabled = False
        cmbCondicionesVenta.Enabled = False
        cmbUMedida.Enabled = False
        cmbIVA.Enabled = False
        txtNumeroDocumento.Enabled = False
        btnGenerarXML.Visible = False
        btnGuardar.Visible = True
        Me.Show()
    End Sub

    Public Sub showManualMode()
        cmbTipoDocumento.Enabled = True
        cmbCondicionIVA.Enabled = True
        cmbCondicionesVenta.Enabled = True
        cmbUMedida.Enabled = True
        cmbIVA.Enabled = True
        txtNumeroDocumento.Enabled = True
        btnGenerarXML.Visible = True
        btnGuardar.Visible = False
        Me.Show()
    End Sub
    Private Sub cmbTipo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbTipo.SelectedIndexChanged
        If constantsUtil.comprobanteCondicionIva(cmbTipo.SelectedItem) = "A" Then
            comunes.populateCombobox(DAOFactory.getConstanteDAO.getConstantes("facturacion", "condicion_iva_a"), "valor", "codigo", cmbCondicionIVA)
        Else
            comunes.populateCombobox(DAOFactory.getConstanteDAO.getConstantes("facturacion", "condicion_iva_b"), "valor", "codigo", cmbCondicionIVA)
        End If

        updateUltimoNumeroComprobante()

    End Sub



    Private Sub btnBorrarItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBorrarItem.Click
        For Each row In grdItems.SelectedRows
            grdItems.Rows.Remove(row)
        Next

    End Sub


    Private Sub btnBorrarTodo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBorrarTodo.Click
        grdItems.Rows.Clear()
    End Sub

    Private Sub itemList_Change(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim total As Double
        For Each item In itemList
            total = total + item.precio_total_bruto
        Next
        txtTotal.Text = total
        If txtPago.Text <> "" Then
            txtVuelto.Text = CDbl(txtPago.Text) - total
        End If
    End Sub

    Private Sub grdItems_RowHeaderMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles grdItems.RowHeaderMouseDoubleClick
        Dim item As comprobanteItem = itemList.Item(grdItems.CurrentCell.RowIndex)
        txtCantidad.Text = item.cantidad
        cmbUMedida.SelectedIndex = cmbUMedida.FindString(item.unidad_medida_valor)
        cmbCodigo.Text = item.codigo
        txtDescripcion.Text = item.descripcion
        cmbNumeroDespacho.Text = item.numero_despacho
        cmbIVA.SelectedIndex = cmbIVA.FindString(item.iva_valor)
        txtPrecioNeto.Text = item.precio_neto
        txtPrecioBruto.Text = item.precio_bruto
    End Sub

    Private Sub btnModificarItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnModificarItem.Click


        Try
            Dim item1 As comprobanteItem = createItem()
            Dim item2 As comprobanteItem = itemList.Item(grdItems.CurrentCell.RowIndex)
            item2.cantidad = item1.cantidad
            item2.producto = item1.producto
            item2.descripcion = item1.descripcion
            item2.stock = item1.stock
            item2.precio_neto = item1.precio_neto
            itemList.ResetBindings()
        Catch ex As Exception
            MsgBox(ex.Message, vbExclamation, "TodoMicro Solution Pack")
        End Try
    End Sub


    Private Sub btnAgregarItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarItem.Click
        Try
            itemList.Add(createItem)
        Catch ex As Exception
            MsgBox(ex.Message, vbExclamation, "TodoMicro Solution Pack")
        End Try

    End Sub


    Private Function createItem() As comprobanteItem

        Dim cantidad As Double
        Dim precioneto As Double

        Try
            cantidad = CDbl(txtCantidad.Text)
        Catch ex As Exception
            Throw New ApplicationException("La cantidad debe ser un valor numerico", ex)
        End Try

        Try
            precioneto = CDbl(txtPrecioNeto.Text)
        Catch ex As Exception
            Throw New ApplicationException("El precio neto debe ser un valor numerico", ex)
        End Try

        If DirectCast(cmbNumeroDespacho.SelectedItem, stock).cantidad < CDbl(txtCantidad.Text) Then Throw New ArgumentException("La cantidad supera la cantidad disponible: " & DirectCast(cmbNumeroDespacho.SelectedItem, stock).cantidad)

        Dim item As comprobanteItem = New comprobanteItem(cantidad, cmbCodigo.SelectedItem, txtDescripcion.Text, cmbNumeroDespacho.SelectedItem, precioneto)

        Dim validates() As InvalidValue = NhibernateValidator.getValidator.Validate(item)

        If validates.Count <> 0 Then
            Dim errors As String = ""
            For Each v In validates
                errors = errors + v.PropertyPath + ": " + v.Message + vbNewLine
            Next
            Throw New ApplicationException(errors)
        End If
        Return item
    End Function
    Private Sub txtPago_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPago.TextChanged
        txtVuelto.Text = IIf(txtPago.Text = "", 0, CDbl(txtPago.Text)) - CDbl(txtTotal.Text)
    End Sub

    Private Sub txtPrecioBruto_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPrecioBruto.LostFocus
        If IsNumeric(txtPrecioBruto.Text) Then
            If txtPrecioBruto.Text <> "" Then
                txtPrecioNeto.Text = Math.Round(CDbl(txtPrecioBruto.Text) / (CDbl(cmbIVA.Text) / 100 + 1), 2)
            End If
        Else
            MsgBox("Solo se aceptan numeros en el campo precio bruto")
            txtPrecioBruto.Text = ""
        End If

    End Sub
    Private Sub cmbIVA_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbIVA.SelectedIndexChanged
        If txtPrecioBruto.Text <> "" Then
            txtPrecioNeto.Text = Math.Round(CDbl(txtPrecioBruto.Text) / (CDbl(cmbIVA.Text) / 100 + 1), 2)
        ElseIf txtPrecioNeto.Text <> "" Then
            txtPrecioBruto.Text = Math.Round(CDbl(txtPrecioNeto.Text) * (CDbl(cmbIVA.Text) / 100 + 1), 2)
        End If
    End Sub

    Private Sub txtPrecioNeto_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPrecioNeto.LostFocus
        actualizarPrecioBruto()
    End Sub

    Private Sub actualizarPrecioBruto()
        If IsNumeric(txtPrecioNeto.Text) Then
            If txtPrecioNeto.Text <> "" Then
                txtPrecioBruto.Text = Math.Round(CDbl(txtPrecioNeto.Text) * (CDbl(cmbIVA.Text) / 100 + 1), 2)
            End If
        Else
            MsgBox("Solo se aceptan numeros en el campo precio neto")
            txtPrecioBruto.Text = ""
        End If
    End Sub

    Private Sub cmbCodigo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbCodigo.SelectedIndexChanged
        Dim producto As producto = cmbCodigo.SelectedItem
        txtDescripcion.Text = producto.descripcion
        cmbUMedida.SelectedValue = producto.unidad_medida.codigo
        comunes.populateDepositosCombobox(producto.id, cmbDeposito)
        comunes.populateCombobox(DAOFactory.getStockDAO.getStocks(producto, cmbDeposito.SelectedValue), "despacho_id", "id", cmbNumeroDespacho)
        cmbIVA.SelectedValue = producto.iva.codigo
        txtPrecioNeto.Text = Math.Round(producto.getPrecioPorlista(0).precio_neto, 2)
        actualizarPrecioBruto()
    End Sub

    Private Sub cmbDeposito_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbDeposito.SelectedIndexChanged
        Dim producto As producto = cmbCodigo.SelectedItem
        comunes.populateCombobox(DAOFactory.getStockDAO.getStocks(producto, cmbDeposito.SelectedValue), "despacho_id", "id", cmbNumeroDespacho)
    End Sub

    Private Sub updateUltimoNumeroComprobante()
        Try
            If Not isLoading Then
                Dim comprobante As comprobante = DAOFactory.getComprobanteDAO.getUltimoComprobante(cmbTipo.SelectedItem, cmbPuntoVenta.SelectedItem, DAOFactory.getEmpresaDAO.FindByID(1))
                If Not comprobante Is Nothing Then
                    txtNumeroComprobante.Text = comprobante.numero_comprobante + 1
                Else
                    txtNumeroComprobante.Text = 0
                End If
            End If

        Catch ex As Exception
            MsgBox("No fue posible obtener el proximo numero de comprobante:" + ex.Message)
        End Try
    End Sub

    Private Sub btnGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGuardar.Click
        Try
            miComprobante.emisor = DAOFactory.getEmpresaDAO.FindByID(1)
            miComprobante.tipo_comprobante = cmbTipo.SelectedItem
            miComprobante.punto_venta = cmbPuntoVenta.SelectedItem
            miComprobante.numero_comprobante = CInt(txtNumeroComprobante.Text)
            miComprobante.concepto = DAOFactory.getConstanteDAO.FindByID(23) 'Poductos
            miComprobante.fecha_vto_cae = dtpFecha.Value
            miComprobante.fecha_comprobante = dtpFecha.Value
            miComprobante.fecha_vto_pago = dtpFecha.Value
            miComprobante.fecha_srv_desde = dtpFecha.Value
            miComprobante.fecha_srv_hasta = dtpFecha.Value
            miComprobante.receptor = cliente
            miComprobante.moneda_cotizacion = 1
            miComprobante.moneda = DAOFactory.getConstanteDAO.FindByID(65) 'pesos
            miComprobante.importe_operaciones_exentas = 0
            miComprobante.importe_otros_tributos = 0
            miComprobante.importe_total_no_gravados = 0
            miComprobante.cae = txtCAE.Text

            miComprobante.items.Clear()
            For Each i In itemList
                miComprobante.addItem(i)
            Next

            If Not NhibernateValidator.getValidator.IsValid(miComprobante) Then
                validationUtils.getValidationMsg(miComprobante)
                Return
            End If

        Catch ex As Exception
            MsgBox("Error cargando el comprobante: " & ex.Message)
        End Try



        Dim miTransaccion As ITransaction = Session.BeginTransaction
        Try
            DAOFactory.getComprobanteDAO.SaveOrUpdate(miComprobante)
            miTransaccion.Commit()
            Session.Evict(cliente)
            Session.Evict(miComprobante)
            MsgBox("El comprobante fue guardado con exito en la base de datos", vbOKOnly, "TodoMicro Solution Pack")
        Catch ex As Exception
            miTransaccion.Rollback()
            MsgBox("No fue posible guardar el comprobante " & ex.Message, vbExclamation, "TodoMicro Solution Pack")
            _session = Nothing
            loadAll()
        Finally
            miTransaccion.Dispose()
        End Try

        Try
            DAOFactory.getComprobanteDAO.comprobanteToXML(miComprobante, configManager.facturaXmlPath + "\" + cmbTipo.Text + "-" + cmbPuntoVenta.Text + "-" + txtNumeroComprobante.Text + ".xml")
        Catch ex As Exception
            MsgBox("No fue generada la salida XML: " & ex.Message)
        End Try

        blankFrm()
    End Sub
    Private Sub blankFrm()
        txtRazonSocial.Text = ""
        txtDomicilio.Text = ""
        txtNumeroDocumento.Text = ""
        itemList.Clear()
        miComprobante = New comprobante
        cliente = Nothing
        updateUltimoNumeroComprobante()
        btnEliminar.Visible = False
    End Sub

    Private Sub cmbProvincia_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbProvincia.SelectedIndexChanged
        comunes.populateCombobox(DAOFactory.getLocalidadDAO.getLocalidadesPorProvincia(cmbProvincia.SelectedItem), "nombreAMostrar", "id", cmbLocalidad)
    End Sub

    Private Sub btnSeleccionarcliente_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSeleccionarcliente.Click
        cliente = comunes.getCliente(Session)
        cargarCliente(cliente)

    End Sub

    Private Sub txtNumeroComprobante_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNumeroComprobante.LostFocus
        If Integer.Parse(txtNumeroComprobante.Text) < 1 Then
            MsgBox("El numero de comprobante debe ser un entero mayor a cero", vbExclamation, "TodoMicroSolutionPack")
        End If
    End Sub

    Private Sub btnNuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNuevo.Click
        blankFrm()
    End Sub
    Private Sub btnCargarExistente_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCargarExistente.Click
        miComprobante = comunes.getComprobante(Session)
        If miComprobante Is Nothing Then
            miComprobante = New comprobante()
        Else
            btnEliminar.Visible = True
            comprobanteToFrm()
        End If
    End Sub
    Private Sub comprobanteToFrm()
        cargaItems(miComprobante.items)
        cargarCliente(miComprobante.receptor)
        cmbTipo.SelectedIndex = cmbTipo.FindStringExact(miComprobante.tipo_comprobante.valor)
        cmbPuntoVenta.SelectedIndex = cmbPuntoVenta.FindStringExact(miComprobante.punto_venta.numero)
        txtNumeroComprobante.Text = miComprobante.numero_comprobante
        txtCAE.Text = miComprobante.cae
    End Sub
    Private Sub cargarCliente(ByRef cliente As entidad)
        If Not IsNothing(cliente) Then
            txtRazonSocial.Text = cliente.razon_social
            txtDomicilio.Text = cliente.domicilio
            cmbProvincia.SelectedIndex = cmbProvincia.FindStringExact(cliente.localidad.departamento.provincia.nombre)
            cmbLocalidad.SelectedIndex = cmbLocalidad.FindStringExact(cliente.localidad.nombreAMostrar)
            If cliente.esResponsableIscripto Then
                cmbTipo.SelectedIndex = cmbTipo.FindString("Factura A")
            Else
                cmbTipo.SelectedIndex = cmbTipo.FindString("Factura B")
            End If
            cmbCondicionIVA.SelectedIndex = cmbCondicionIVA.FindStringExact(cliente.posicion_iva.valor)
            cmbTipoDocumento.SelectedIndex = cmbTipoDocumento.FindStringExact(cliente.tipo_documento.valor)
            txtNumeroDocumento.Text = cliente.numero_documento
        End If
    End Sub
    Private Sub cargaItems(ByRef items As ICollection(Of comprobanteItem))
        itemList.Clear()

        For Each item In items
            itemList.Add(item)
        Next

    End Sub

    Private Sub btnGenerarXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerarXML.Click
        Dim total_iva105 As Double
        Dim base_iva105 As Double
        Dim total_iva21 As Double
        Dim base_iva21 As Double
        Dim total_bruto As Double
        Dim total_neto As Double

        For Each item In itemList
            total_bruto = total_bruto + item.precio_total_bruto
            total_neto = total_neto + item.precio_total_neto
            If item.iva_valor = 21 Then
                total_iva21 = total_iva21 + item.importe_iva_total
                base_iva21 = base_iva21 + item.precio_total_neto
            Else
                total_iva105 = total_iva105 + item.importe_iva_total
                base_iva105 = base_iva105 + item.precio_total_neto
            End If
        Next

        Dim settings As XmlWriterSettings = New XmlWriterSettings()
        settings.Indent = True
        Using writer As XmlWriter = XmlWriter.Create(configManager.facturaXmlPath + "\" + cmbTipo.Text + "-" + cmbPuntoVenta.Text + "-" + txtNumeroComprobante.Text + ".xml", settings)
            ' Begin writing.
            writer.WriteStartDocument()
            writer.WriteStartElement("comprobantes")
            writer.WriteStartElement("comprobante")

            writer.WriteElementString("concepto", "1")
            writer.WriteElementString("condicion_frente_iva", cmbCondicionIVA.SelectedValue)
            writer.WriteElementString("idimpositivoreceptor", DirectCast(cmbCondicionIVA.SelectedItem, constante).valor)
            writer.WriteElementString("domicilioreceptor", txtDomicilio.Text)
            writer.WriteElementString("importetotal", Math.Round(total_bruto, 2))
            writer.WriteElementString("localidadreceptor", cmbLocalidad.Text)
            writer.WriteElementString("fechaservdesde", "")
            writer.WriteElementString("receptor", txtRazonSocial.Text)
            writer.WriteElementString("reproceso", "N")
            writer.WriteElementString("nrodocreceptor", txtNumeroDocumento.Text)
            writer.WriteElementString("motivo", "")
            writer.WriteElementString("id", "")
            writer.WriteStartElement("tributos")
            'writer.WriteStartElement("tributo")
            'writer.WriteElementString("desc", "impuesto municipal ....")
            'writer.WriteElementString("alic", "1")
            'writer.WriteElementString("baseimp", "1000")
            'writer.WriteElementString("id", "99")
            'writer.WriteElementString("importe", "10")
            'writer.WriteEndElement()
            writer.WriteEndElement()
            writer.WriteElementString("otrosdatoscomerciales", "")
            writer.WriteElementString("tipocambio", "1.000000")
            writer.WriteElementString("tipo", cmbTipo.SelectedValue)
            writer.WriteElementString("numero_cotizacion", "")
            writer.WriteStartElement("detalles")
            For Each item In itemList
                writer.WriteStartElement("detalle")
                writer.WriteElementString("importe", Math.Round(item.precio_total_bruto, 2))
                writer.WriteElementString("unimed", item.unidad_medida_codigo)
                writer.WriteElementString("numero_despacho", item.numero_despacho)
                writer.WriteElementString("cant", item.cantidad)
                writer.WriteElementString("preciounit", Math.Round(item.precio_neto, 2))
                writer.WriteElementString("tasaiva", item.iva_codigo)
                writer.WriteElementString("importeiva", Math.Round(item.precio_bruto - item.precio_neto, 2))
                writer.WriteElementString("ncm", "")
                writer.WriteElementString("sec", "")
                writer.WriteElementString("bonificacion", "")
                writer.WriteElementString("desc", item.descripcion)
                writer.WriteElementString("cod", item.codigo)
                writer.WriteEndElement()
            Next
            writer.WriteEndElement()
            writer.WriteElementString("numero_cliente", "")
            writer.WriteElementString("ptovta", cmbPuntoVenta.Text)
            writer.WriteElementString("fechaemision", dtpFecha.Value.Year.ToString.Trim.PadLeft(4, "0") & dtpFecha.Value.Month.ToString.Trim.PadLeft(2, "0") & dtpFecha.Value.Day.ToString.Trim.PadLeft(2, "0"))
            writer.WriteElementString("numero_remito", "")
            writer.WriteElementString("tipodocreceptor", cmbTipoDocumento.SelectedValue)
            writer.WriteElementString("importeopex", "0.00")
            writer.WriteElementString("numero", txtNumeroComprobante.Text)
            writer.WriteElementString("importeiva", Math.Round(total_iva21 + total_iva105, 2))
            writer.WriteElementString("fechaservhasta", "")
            writer.WriteElementString("otrosdatosgenerales", "")
            writer.WriteElementString("cuitemisor", "20325363046")
            writer.WriteElementString("importetotalconcepto", "0.00")
            writer.WriteElementString("importetributos", "0.00")
            writer.WriteElementString("resultado", "")
            writer.WriteElementString("provinciareceptor", cmbProvincia.Text)
            writer.WriteStartElement("ivas")
            If total_iva105 > 0 Then
                writer.WriteStartElement("iva")
                writer.WriteElementString("baseimp", Math.Round(base_iva105, 2))
                writer.WriteElementString("id", "4")
                writer.WriteElementString("importe", Math.Round(total_iva105, 2))
                writer.WriteEndElement()
            End If
            If total_iva21 > 0 Then
                writer.WriteStartElement("iva")
                writer.WriteElementString("baseimp", Math.Round(base_iva21, 2))
                writer.WriteElementString("id", "5")
                writer.WriteElementString("importe", Math.Round(total_iva21, 2))
                writer.WriteEndElement()
            End If
            writer.WriteEndElement()
            writer.WriteElementString("fechavencpago", "")
            writer.WriteStartElement("formaspago")
            writer.WriteStartElement("formapago")
            writer.WriteElementString("descripcion", "efectivo")
            writer.WriteElementString("codigo", "")
            writer.WriteEndElement()
            writer.WriteEndElement()
            writer.WriteElementString("importeneto", Math.Round(total_neto, 2))
            writer.WriteElementString("moneda", "PES")
            writer.WriteElementString("fecha_vto", "")
            writer.WriteElementString("idioma", "1")
            writer.WriteElementString("cae", "")
            writer.WriteElementString("numero_orden_compra", "")
            writer.WriteEndElement()
            writer.WriteEndElement()
            writer.WriteEndDocument()
        End Using
        MsgBox("Archivo generado con exito", vbOKOnly, "TodoMicroSolutionPack")
    End Sub

    Private Sub frmComprobanteEdit_ImeModeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.ImeModeChanged

    End Sub

    Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminar.Click


        If miComprobante.id = 0 Then
            MsgBox("No es un comprobante previamente guardado", vbExclamation, "TodoMicro Solution Pack")
            Return
        End If

        If (MsgBox("¿Esta seguro que desea eliminar el comprobante? Esta operación sera irreversible", vbYesNo, "TodoMicro Solution Pack")) = vbNo Then
            Return
        End If


        Dim miTransaccion As ITransaction = Session.BeginTransaction
        Try
            DAOFactory.getComprobanteDAO.Delete(miComprobante)
            miTransaccion.Commit()
            MsgBox("Comprobante eliminado con exito: ", vbOK, "TodoMicro Solution Pack")
        Catch ex As Exception
            miTransaccion.Rollback()
            _session = Nothing
            MsgBox("No se pudo eliminar el comprobante: " & ex.Message, vbExclamation, "TodoMicro Solution Pack")
        Finally
            miTransaccion.Dispose()
            loadAll()
        End Try
        blankFrm()
    End Sub

    Private Sub txtPrecioBruto_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPrecioBruto.TextChanged

    End Sub

    Private Sub btnPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreview.Click

        Dim barcode As String = miComprobante.emisor.cuit.ToString & miComprobante.tipo_comprobante.codigo.PadLeft(2, "0") & miComprobante.punto_venta.numero.ToString.PadLeft(4, "0") & miComprobante.cae & Format(miComprobante.fecha_vto_cae, "yyyyMMdd")
        barcode = barcode & comunes.barCodeDigitoVerificador(barcode)

        Dim barcodeCodificado As String = comunes.convertTo2of5BarCode(barcode)

        Dim txtBarCode As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtBarCodeLegible As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtCAE As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtVtoCae As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtTotal As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtIVA105 As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtIVA21 As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtSubTotal As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtObs As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtFormaPago As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtCondicionIvaReceptor As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtCuitReceptor As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtLocalidad As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtProvincia As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtDireccion As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtRazonSocialReceptor As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtTipoComprobante As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtFecha As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtNumero As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtLetraComprobante As CrystalDecisions.CrystalReports.Engine.TextObject
        Dim txtCodigoTipoComprobante As CrystalDecisions.CrystalReports.Engine.TextObject

        txtBarCode = rpt.ReportDefinition.ReportObjects("txtBarCode")
        txtBarCodeLegible = rpt.ReportDefinition.ReportObjects("txtBarCodeLegible")
        txtCAE = rpt.ReportDefinition.ReportObjects("txtCAE")
        txtVtoCae = rpt.ReportDefinition.ReportObjects("txtVtoCAE")
        txtTotal = rpt.ReportDefinition.ReportObjects("txtTotal")
        txtIVA105 = rpt.ReportDefinition.ReportObjects("txtIVA105")
        txtIVA21 = rpt.ReportDefinition.ReportObjects("txtIVA21")
        txtSubTotal = rpt.ReportDefinition.ReportObjects("txtSubTotal")
        txtObs = rpt.ReportDefinition.ReportObjects("txtObs")
        txtFormaPago = rpt.ReportDefinition.ReportObjects("txtFormaPago")
        txtCondicionIvaReceptor = rpt.ReportDefinition.ReportObjects("txtCondicionIvaReceptor")
        txtCuitReceptor = rpt.ReportDefinition.ReportObjects("txtCuitReceptor")
        txtLocalidad = rpt.ReportDefinition.ReportObjects("txtLocalidad")
        txtProvincia = rpt.ReportDefinition.ReportObjects("txtProvincia")
        txtDireccion = rpt.ReportDefinition.ReportObjects("txtDireccion")
        txtRazonSocialReceptor = rpt.ReportDefinition.ReportObjects("txtRazonSocialReceptor")
        txtTipoComprobante = rpt.ReportDefinition.ReportObjects("txtTipoComprobante")
        txtFecha = rpt.ReportDefinition.ReportObjects("txtFecha")
        txtNumero = rpt.ReportDefinition.ReportObjects("txtNumero")
        txtLetraComprobante = rpt.ReportDefinition.ReportObjects("txtLetraComprobante")
        txtCodigoTipoComprobante = rpt.ReportDefinition.ReportObjects("txtCodigoTipoComprobante")

        txtBarCode.Text = barcodeCodificado
        txtBarCodeLegible.Text = barcode
        txtCAE.Text = miComprobante.cae
        txtVtoCae.Text = Format(miComprobante.fecha_vto_cae, "dd/MM/yyyy")
        txtTotal.Text = miComprobante.importe_total
        txtIVA105.Text = miComprobante.importe_iva105
        txtIVA21.Text = miComprobante.importe_iva21
        txtSubTotal.Text = miComprobante.importe_neto
        txtObs.Text = miComprobante.observaciones
        txtFormaPago.Text = "Efectivo"
        txtCondicionIvaReceptor.Text = miComprobante.receptor.posicion_iva.valor
        txtCuitReceptor.Text = miComprobante.receptor.numero_documento
        txtLocalidad.Text = miComprobante.receptor.localidad.nombre
        txtProvincia.Text = miComprobante.receptor.localidad.departamento.provincia.nombre
        txtDireccion.Text = miComprobante.receptor.domicilio
        txtRazonSocial.Text = miComprobante.receptor.razon_social
        txtTipoComprobante.Text = miComprobante.tipo_comprobante.valor
        txtFecha.Text = Format(miComprobante.fecha_comprobante, "dd/MM/yyyy")
        txtNumero.Text = miComprobante.punto_venta.numero.ToString.PadLeft(4, "0") & "-" & miComprobante.numero_comprobante.ToString.PadLeft(8, "0")
        txtLetraComprobante.Text = constantsUtil.comprobanteLetra(miComprobante.tipo_comprobante)
        txtCodigoTipoComprobante.Text = "COD. " & miComprobante.tipo_comprobante.codigo.PadLeft(2, "0")

        rpt.SetDataSource(miComprobante.items.ToArray)

        frmComprobanteViewer.CRViewer.ReportSource = rpt
        frmComprobanteViewer.MdiParent = Me.MdiParent
        frmComprobanteViewer.Show()
        frmComprobanteViewer.CRViewer.Refresh()
    End Sub
End Class
